package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.gateway.utils.threadlocal.WmThreadLocalUtils;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 王可
 * @Date: 2021/01/28/17:52
 * @Description:
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Resource
    private FastDFSClient fastDFSClient;

    @Value("${fdfs.web-server-url}")
    private String fileServerUrl;

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 新增图片
     * @param multipartFile
     * @return
     */
    @Override
    @Transactional
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1. 检查参数
        if (multipartFile == null || StringUtils.isEmpty(multipartFile.getOriginalFilename())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 获取当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3. 将文件上传到fastDFS
        try {
            String fileId = fastDFSClient.uploadFile(multipartFile);
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());
            wmMaterial.setUrl(fileId);
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);

            // 为了前端回显  给图片加上前缀路径
            wmMaterial.setUrl(fileServerUrl + fileId);

            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败");
        }
    }

    /**
     * 查询图片
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult findList(WmMaterialDto dto) {
        //检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

       //封装查询条件
        //封装分页条件
        Page<WmMaterial> pageResult = new Page<>(dto.getPage(),dto.getSize());

        //封装查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();

        //被收藏条件查询
        if(dto.getIsCollected() != null && dto.getIsCollected() == 1){
            queryWrapper.eq(WmMaterial::getIsCollection, 1);
        }

        //执行查询
        IPage<WmMaterial> pageResponse = page(pageResult, queryWrapper);

        ResponseResult pageResponseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)pageResponse.getTotal());

        //将图片添加上代理地址
        List<WmMaterial> records = pageResponse.getRecords();
        records = records.stream().map((item) -> {
            item.setUrl(fileServerUrl + item.getUrl());
            return item;
        }).collect(Collectors.toList());

        pageResponseResult.setData(records);

        return pageResponseResult;
    }


    /**
     * 删除图片
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ResponseResult delPicture(Integer id) {
        //检查参数
        if(id == null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

       //判断素材有没有被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getMaterialId, id)
        );
        if(count!= null && count > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"图片被引用！无法删除");
        }

        //需要登录才能删除自己上传的图片
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //根据用户id查询出图片信息
        WmMaterial wmMaterial = getOne(Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getId, id));

        //删除 fastDFS中的图片
        fastDFSClient.delFile(wmMaterial.getUrl());

        //删除表格中的图片信息
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消收藏
     * @param id
     * @param weatherColloection
     * @return
     */
    @Override
    @Transactional
    public ResponseResult updateStatus(Integer id, Short weatherColloection) {

        //检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //跟新状态
       update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,weatherColloection )
                        .eq(WmMaterial::getUserId,user.getId())
                        .eq(WmMaterial::getId, id)
       );
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
